package com.pansoft.openplanet.fragment;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.event.RightTopMenuClickEvent;
import com.efounder.frame.baseui.BaseFragment;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.activity.WalletAvatarAndNameSetupActivity;
import com.pansoft.openplanet.activity.WalletTypeSelectActivity;
import com.pansoft.openplanet.adapter.ChildACTWalletListAdapter;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.AssetListBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.widget.StarAssetWalletPopup;
import com.pansoft.openplanet.widget.WrapContentLinearLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * achain 钱包列表
 *
 * @author YQS
 */
public class ActWalletListFragment extends BaseFragment implements View.OnClickListener {


    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;


    private LinearLayout llEmptyLayout;
    private Button tvCreateWallet;
    private Button tvRestoreWallet;
    private ImageView ivIcon;
    private TextView tvTextTitle;

    private Account currentAccout;
    private ChildACTWalletListAdapter childWalletListAdapter;

    private ArrayList<AssetListBean> assetList = new ArrayList<>();//当前关注的代币列表
    private int mode = IPAssetsConstant.CHAIN_ID_ACT;
    private String balance = "0";//钱包余额


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.open_planet_fragment_wallet_list, container, false);
        initView(rootView);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initView(View rootView) {
        recyclerView = rootView.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        llEmptyLayout = (LinearLayout) rootView.findViewById(R.id.ll_empty_layout);
        tvCreateWallet = (Button) rootView.findViewById(R.id.tv_create_wallet);
        tvRestoreWallet = (Button) rootView.findViewById(R.id.tv_restore_wallet);
        ivIcon = (ImageView) rootView.findViewById(R.id.iv_icon);
        tvTextTitle = (TextView) rootView.findViewById(R.id.tv_text_title);
        tvRestoreWallet.setOnClickListener(this);
        tvCreateWallet.setOnClickListener(this);
        refreshLayout = rootView.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(false);//开启自动加载功能（非必须）
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                initData();
            }
        });

        childWalletListAdapter = new ChildACTWalletListAdapter(getContext(), assetList, mode);
        recyclerView.setAdapter(childWalletListAdapter);

    }


    private void initData() {
        //请求钱包余额
        AccountDao accountDao = new AccountDao(getActivity());
        Account account = accountDao.getCurrentShowAccount(IPAssetsConstant.ChainEnum.ACHAIN);
        if (account == null) {
            List<Account> accounts = accountDao.getAllChildAccount(IPAssetsConstant.ChainEnum.ACHAIN);
            if (accounts.size() == 0) {
                //本地没有账户 显示创建的views
                refreshLayout.setVisibility(View.GONE);
                llEmptyLayout.setVisibility(View.VISIBLE);
                ivIcon.setImageDrawable(getResources().getDrawable(R.drawable.ipasset_wallet_list_act));
                tvTextTitle.setText("ACT");
                return;
            } else {
                account = accounts.get(0);
                account.setCurrentShow(true);
                accountDao.insertOrReplace(account);
                refreshLayout.setVisibility(View.VISIBLE);
                llEmptyLayout.setVisibility(View.GONE);
            }
        }
        currentAccout = account;
        String address = account.getAddress();
        requestOtherData(address);

    }

    //请求其他数据
    private void requestOtherData(String address) {
        assetList.clear();
        //添加头部区域
        assetList.add(new AssetListBean.Builder().type(1).build());
        //添加第一条数据ACT
        assetList.add(new AssetListBean.Builder().build());
        childWalletListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_create_wallet) {
            WalletAvatarAndNameSetupActivity.start(getActivity(), WalletTypeSelectActivity.MODE_CREATE_NEW,
                    IPAssetsConstant.CHAIN_ID_ACT);
        } else if (id == R.id.tv_restore_wallet) {

            WalletAvatarAndNameSetupActivity.start(getActivity(), WalletTypeSelectActivity.MODE_RESTORE_OLD,
                    IPAssetsConstant.CHAIN_ID_ACT);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWalletChanged(Account account) {
        initData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void rightTopMenuClickEvent(RightTopMenuClickEvent event) {
        StubObject stubObject = (StubObject) event.getStubObject();
        String id = stubObject.getObject("id", "").toString();
        if (id.equals("act")) {
            StarAssetWalletPopup.showPopup(getActivity(), event.getView(), IPAssetsConstant.CHAIN_ID_ACT);
        }
    }
}
